package com.spzx.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    IPaymentInfoService paymentInfoService;

    @Override
    public String submitAlipay(String orderNo) {
        //保存支付信息
        PaymentInfo paymentInfo=paymentInfoService.savePayment(orderNo);
        //调用支付接口：alipay.trade.wap.pay(手机网站支付接口2.0)
        try {
            AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
            alipayTradeWapPayRequest.setReturnUrl(AlipayConfig.return_payment_url);
            alipayTradeWapPayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("out_trade_no",paymentInfo.getOrderNo()); //商户订单号
            hashMap.put("product_code","QUICK_WAP_WAY"); //签约的支付产品类型
            hashMap.put("total_amount",paymentInfo.getAmount());
            hashMap.put("subject",paymentInfo.getContent());
            hashMap.put("time_expire","2025-08-16 12:00:00"); //设置订单绝对超时时间
            alipayTradeWapPayRequest.setBizContent(JSON.toJSONString(hashMap));
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(alipayTradeWapPayRequest, "post");
            String h5Form = response.getBody();
            return h5Form;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new ServiceException("调用支付接口失败");
        }
    }
}
